import * as types from './actionTypes';

import {ToastAndroid} from 'react-native';

const login = (email,password,callback,saveTickket) => {
  return (dispatch, getStore) => {


     dispatch({
        type: types.Login
     });

      fetch('http://42.159.143.17:6080/alfresco/service/api/login?u='+email+'&pw='+password+'&format=json',{
           method: 'GET'
          })
      .then(res => {
        if (res.status >= 400) {
         ToastAndroid.show("账号或密码错误",ToastAndroid.SHORT);
         dispatch({
            type: types.LoginFail
         });
          throw new Error("Failed to retreive");
        }
        return res.json();
      })
      .then(token => {
      dispatch({
     	 type: types.LoginSuccess,
     	 token
      });
      let ticket = token.data.ticket;

      dispatch({
        type: types.UpdateTicket,
        ticket
      })


      callback();

      saveTickket(token.data.ticket);
    // alert(token.data.ticket);

      })
      .catch(error => {
        console.log('ERRORR');
      });
    //  alert(email);dsds   sadsa
	 }
 }
const updateTicket = function(ticket){
  return {
    type: types.UpdateTicket,
    ticket
  }
}

export default {
   login,
   updateTicket
}
